package com.qyhl.module_home.city.bestone.ontype;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.TypedValue;
import android.view.View;

import com.qyhl.webtv.commonlib.entity.home.BestoneItemTypeBean;

import java.util.ArrayList;

public class BestoneItemDecoration extends RecyclerView.ItemDecoration {
    /**
     * 数据列表
     */
    private ArrayList<BestoneItemTypeBean> datas;
    /**
     * 标题栏和悬浮栏高度
     */
    private int titleHeight;

    /**
     * 标题栏和悬浮栏画笔
     */
    private Paint mPaint;
    /**
     * 控制字体居中的偏移量，最终y坐标要减掉这个偏移量字体才会纵向居中
     */
    private float textOffset;

    public BestoneItemDecoration(ArrayList<BestoneItemTypeBean> datas, Context context) {
        this.datas = datas;
        titleHeight = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 32, context.getResources().getDisplayMetrics());
        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setAntiAlias(true);
        mPaint.setTextAlign(Paint.Align.LEFT);
        mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setTextSize(TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_SP, 18, context.getResources().getDisplayMetrics()));
        Paint.FontMetrics fontMetrics = mPaint.getFontMetrics();
        textOffset = fontMetrics.top / 2 + fontMetrics.bottom / 2;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        int position = ((RecyclerView.LayoutParams) view.getLayoutParams()).getViewLayoutPosition();
        //position在重置时可能为-1.保险点判断一下吧
        if (position > -1) {
            if (position == 0) {
                //等于0肯定要有title的
                setBottom(outRect, titleHeight, position);
            } else {
                //其他的通过判断
                if (datas.get(position).getFirstPinYin() != datas.get(position - 1).getFirstPinYin()) {
                    //不为空 且跟前一个tag不一样了，说明是新的分类，也要title
                    setBottom(outRect, titleHeight, position);
                } else {
                    setBottom(outRect, 0, position);
                }
            }
        }
    }

    private void setBottom(Rect outRect, int titleHeight, int position) {
        if (datas.size() > position + 1) {
            if (datas.get(position).getFirstPinYin() != datas.get(position + 1).getFirstPinYin()) {
                outRect.set(0, titleHeight, 0, 0);
            } else {
                outRect.set(0, titleHeight, 0, 1);
            }
        } else {
            outRect.set(0, titleHeight, 0, 0);
        }
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDraw(c, parent, state);
        final int left = parent.getPaddingLeft();
        final int right = parent.getWidth() - parent.getPaddingRight();
        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
            int position = params.getViewLayoutPosition();
            //position在重置时可能为-1.保险点判断一下吧
            if (position > -1) {
                if (position == 0) {
                    //等于0肯定要有title的
                    drawTitleArea(c, left, right, child, params, position);
                    drawableBottom(c, child, position);
                } else {
                    if (datas.get(position).getFirstPinYin() != datas.get(position - 1).getFirstPinYin()) {
                        //跟前一个tag不一样，说明是新的分类，也要title
                        drawTitleArea(c, left, right, child, params, position);
                    }
                    drawableBottom(c, child, position);
                }
            }
        }
    }

    private void drawTitleArea(Canvas c, int left, int right, View child, RecyclerView.LayoutParams params, int position) {//最先调用，绘制在最下层
        mPaint.setColor(Color.parseColor("#F5F5F5"));
        //画title背景矩形
        c.drawRect(left, child.getTop() - params.topMargin - titleHeight, right,
                child.getTop() - params.topMargin, mPaint);
        mPaint.setColor(Color.parseColor("#1D1D1D"));
        //画文本
        c.drawText(String.valueOf(datas.get(position).getFirstPinYin()),
                child.getPaddingLeft(), child.getTop() - params.topMargin - titleHeight / 2 - textOffset, mPaint);
    }

    private void drawableBottom(Canvas c, View child, int position) {
        mPaint.setColor(Color.parseColor("#E8E8E8"));
        if (datas.size() > position + 1) {
            if (datas.get(position).getFirstPinYin() == datas.get(position + 1).getFirstPinYin()) {
                c.drawLine(child.getLeft() + child.getPaddingLeft(), child.getBottom(),
                        child.getRight() - 88, child.getBottom(), mPaint);
            }
        }
    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDrawOver(c, parent, state);
        int position = ((LinearLayoutManager) (parent.getLayoutManager())).findFirstVisibleItemPosition();
        //出现一个奇怪的bug，有时候child为空，所以将 child = parent.getChildAt(i)。-》 parent.findViewHolderForLayoutPosition(pos).itemView
        View child = parent.findViewHolderForLayoutPosition(position).itemView;

        //定义一个flag，Canvas是否位移过的标志
        boolean flag = false;
        if (datas.size() > position + 1) {
            if (datas.get(position).getFirstPinYin() != datas.get(position + 1).getFirstPinYin()) {
                //当前第一个可见的Item的tag，不等于其后一个item的tag，说明悬浮的View要切换了
                //当getTop开始变负，它的绝对值，是第一个可见的Item移出屏幕的距离，
                if (child.getHeight() + child.getTop() < titleHeight) {
                    //当第一个可见的item在屏幕中还剩的高度小于title区域的高度时，开始做悬浮Title的“交换动画”
                    //每次绘制前 保存当前Canvas状态，
                    c.save();
                    flag = true;

                    //将canvas上移 （y为负数） ,所以后面canvas 画出来的Rect和Text都上移了，有种切换的“动画”感觉
                    c.translate(0, child.getHeight() + child.getTop() - titleHeight);
                }
            }
        }

        mPaint.setColor(Color.parseColor("#F5F5F5"));
        //画悬浮title背景矩形
        c.drawRect(parent.getPaddingLeft(), parent.getPaddingTop(),
                parent.getRight() - parent.getPaddingRight(), parent.getPaddingTop() + titleHeight, mPaint);
        mPaint.setColor(Color.parseColor("#1D1D1D"));
        //画悬浮title文本
        c.drawText(String.valueOf(datas.get(position).getFirstPinYin()), child.getPaddingLeft(),
                titleHeight / 2 - textOffset, mPaint);

        if (flag) {
            c.restore();//恢复画布到之前保存的状态
        }
    }
}
